Added more tests, fixed bug in intersection finding algorithm
[brmtron.git] / BrmTron Server / src / cz / brmlab / brmtron / server / BrmTronServerThread.java
blob4614b1f0d036bb93a4d26a374e4b8aa79483675c
1 package cz.brmlab.brmtron.server;
3 import java.io.BufferedReader;
4 import java.io.DataOutputStream;
5 import java.io.InputStreamReader;
6 import java.net.Socket;
7 import java.util.Map;
8 import java.util.Scanner;
9 import java.util.Set;
11 public class BrmTronServerThread extends Thread {
13 private Socket sock;
14 private int id;
15 private Player player;
18 public BrmTronServerThread(Socket sock, int id){
19 super("BrmTronServerThread");
20 this.sock = sock;
21 this.id = id;
22 this.player = new Player();
25 @Override
26 public void run() {
27 String s;
28 double[] loc = new double[2];
29 try {
30 DataOutputStream out = new DataOutputStream(sock.getOutputStream());
31 BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
33 player.setActive(true);
35 while((s=in.readLine()) != null) {
36 //debug commands
37 if(s.equalsIgnoreCase("die")){
38 player.setActive(false);
40 if(s.equals("quit")) {
41 break;
44 //parse client input
45 Scanner sc = new Scanner(s);
46 for(int i=0;sc.hasNextDouble();i++) {
47 loc[i] = sc.nextDouble();
49 player.setCoords(loc[0], loc[1]);
50 PathElement elem = new PathElement(player.getPrevCoords(), player.getCoords());
52 //collision check
53 double[] tmp = BrmTronServer.checkForCollision(elem);
55 //add a wall; if player has crashed, change his end position to a crash location
56 if(tmp == null) {
57 BrmTronServer.addWall(elem);
58 } else {
59 elem.setEnd(tmp[0], tmp[1]);
60 player.setActive(false);
61 player.setCoords(tmp[0], tmp[1]);
64 //save player state and send him an update
65 BrmTronServer.updatePlayer(id, player);
66 out.writeBytes(parsePlayers(BrmTronServer.getPlayers()));
69 out.close();
70 in.close();
71 sock.close();
72 } catch(Exception e) {
73 System.err.println(e);
78 /**
79 * @param players Numbered list of players
80 * @return String representation of each player's state
82 private String parsePlayers(Map<Integer, Player> players) {
83 String ret = new String();
84 Set<Integer> keys = players.keySet();
86 for(int i: keys) {
87 double[] coords = players.get(i).getCoords();
88 boolean active = players.get(i).isActive();
89 ret += "ID: " + i + ", Long: " + coords[0] + ", Lat: " + coords[1] + ", Active: " + active + "\n";
92 return ret;